# encoding: utf-8
from app.db.models.users import User
from app.db.models.packages import Packages


class JobDownload:

    @staticmethod
    def deal_result(jobs, user_dict, plan_dict):

        data_list = []
        for job in jobs:
            user = user_dict.get(job['uid'], {})
            if not user:
                continue

            is_verified = '已认证' if job['verification'].isVerified else '未认证'
            enable_monitor = '启用' if job['enableMonitor'] else '关闭'
            enable_alert = '启用' if job['enableAlert'] else '关闭'

            try:
                create_time = job['createTime'].strftime("%Y-%m-%d")
            except Exception as e:
                create_time = ''

            item = [job['note'], job['targetUrl'], is_verified, enable_monitor, enable_alert, user.get('username', ''),
                    plan_dict.get(user['planId'], ''), create_time]
            data_list.append(item)

        csv_header = [u'资产名称', u'资产地址', u'认证状态', u'监测状态', u'告警状态', u'所属用户', u'套餐', u'创建时间']

        return {"csv_header": csv_header, "data_list": data_list}

    @staticmethod
    def get_user_dict_by_ids(user_id_list):
        if not user_id_list:
            return dict()

        users = User.objects.only('username', 'planId').filter(pk__in=user_id_list)

        user_dict = dict()
        for user in users:
            user_dict[user.pk] = {
                'username': user['username'],
                'planId': user['planId'],
            }

        user_dict['plan_ids'] = users.distinct('planId')
        return user_dict

    @staticmethod
    def get_plan_dict_by_ids(plan_id_list):
        if not plan_id_list:
            return dict()

        if None in plan_id_list:
            del plan_id_list[plan_id_list.index(None)]

        plan_dict = []
        if plan_id_list:
            plans = Packages.objects.filter(pk__in=plan_id_list)
            plan_dict = {plan.pk: plan['name'] for plan in plans}

        return plan_dict

    def get(self, jobs):
        user_ids = jobs.distinct('uid')
        user_dict = self.get_user_dict_by_ids(user_ids)
        plan_dict = self.get_plan_dict_by_ids(user_dict.get('plan_ids'))
        result = self.deal_result(jobs, user_dict, plan_dict)
        return result
